#include <iostream>
#include <opencv2/opencv.hpp>

#include "FaceDetector.h"

FaceDetector::FaceDetector(const char *faceCascadeFilename) {
    
    this->faceCascade = (CvHaarClassifierCascade *) cvLoad(faceCascadeFilename, 
                                                           0, 0, 0);
    
    if (this->faceCascade == NULL) {
        std::cout << "Cant open " << faceCascadeFilename << std::endl;
    }
    
    this->storage = cvCreateMemStorage(0);
    
    if (this->storage == NULL) {
        std::cout << "Cant create memory storage" << std::endl;
    }
}

FaceDetector::~FaceDetector() {
    cvReleaseHaarClassifierCascade(&(this->faceCascade));
    cvReleaseMemStorage(&(this->storage));
}

CvSeq *FaceDetector::detect(const cv::Mat &image, const cv::Size minFaceSize) {
    CvMat tmp = image;
    assert(image.depth() == CV_8UC1);
    
	cvClearMemStorage(this->storage);
    
    return cvHaarDetectObjects(&tmp, 
                               this->faceCascade, 
                               this->storage, 
                               1.2, 
                               2,
                               CV_HAAR_DO_CANNY_PRUNING,
                               //CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH,
                               cvSize(20,20)); 
    
    /*
    if (rects->total > 0) {
        CvRect rect;
        rect = *(CvRect *) cvGetSeqElem(rects, 0);
        std::cout << "Face found" << std::endl;
    }
    
    cv::rectangle(image, rect, cv::Scalar(255, 0, 0));
     
    */
}
